<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/5/3
 * Time: 17:17
 * Desc: 店内商品
 */
namespace app\store\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use app\store\model\Storegoods as StoregoodsModel;
use app\store\model\StoreOrderGoods;
class Storegoods extends BasicAdmin{
    /**
     * @Author  lingyun
     * @Desc    店内商品
     * 2018-05-03
     */
    public function index(){
        $this->title = '店内商品';
        $get = $this->request->get();
        $store_id = session('user')['store_id'];

        $db = db('goods')->alias('a')->join('ys_goods_category b','a.cat_id=b.id','LEFT')->join('ys_store_goods_stock c','a.id=c.goods_id','Left')->join('ys_goods_spec_detail d','a.id=d.goods_id','LEFT')->order('a.id', 'desc')->where(['a.store_id'=>$store_id,'a.is_deleted'=>0])->field('a.*,b.title,c.stock,c.warn_stock,c.id as stock_id,d.id as spec_id,d.price as dprice,d.member_price as dmember_price,c.trim_price,c.discount,b.title as dtitle,c.goods_spec_id,c.goods_id,d.is_checked');

        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        $store = db('store')->find($store_id);
        $this->assign('store',$store);
        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑
     * 2018-05-03
     */
    public function add_edit(){
        $request = request();
        $Storegoods = new StoregoodsModel();
        if($request->isPost()){
            $post = input('post.');
            $post['store_id'] = session('user')['store_id'];
            $post['addtime'] = time();
            $result = $Storegoods->add_edit($post);
            if($result['code'] == 0){
                $this->error($result['msg'],'');
            }
            $data_arr = [
                'goods_id'=>$result['goods_id'],
                'price'=>$post['price'],
                'member_price'=>$post['price'],
                'stock'=>0,
                'specs'=>0,
                'price'=>$post['price'],
                'member_price'=>$post['member_price'],
                'warn_stock'=>$post['stock'],
                'is_deleted'=>0,
                'addtime'=>time(),
                'is_checked'=>0,
                'store_id'=>session('user')['store_id']
            ];
            $res = db('goods_spec_detail')->where('goods_id',$result['goods_id'])->find();
            if(!empty($res)){
                unset($data_arr['id']);
                db('goods_spec_detail')->where('id',$res['id'])->update($data_arr);
            }else{
                db('goods_spec_detail')->insert($data_arr);
            }

            $result['code'] == 1?$this->success('保存成功',url('@admin').'#'.url('Storegoods/index').'?spm='.input('spm')):$this->error($result['msg'],'');
        }else{
            $id = input('id');
            $info = db('goods')->where('id',$id)->find();
            $category = Db::name('goods_category')->where(['status'=>1,'is_exp'=>0,'is_deleted'=>0])->select();         //商品分类
            $exp_category = Db::name('goods_category')->where(['status'=>1,'is_exp'=>1,'is_deleted'=>0])->select();     //商品扩展分类
            $level = db('sys_level')->order('score asc')->select();

            $this->assign('category',$category);
            $this->assign('exp_category',$exp_category);
            $this->assign('level',$level);            //商品属性名称
            $this->assign('title','编辑商品');
            $this->assign('vo',$info);

            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    分配配方
     * 2018-05-24
     */
    public function fenpei(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $data_arr['peifang_ids'] = implode(',',$post['authorize']);
            $data_arr['id'] = $post['id'];

            $chengben = db('goods_peifang')->where('id','in',$data_arr['peifang_ids'])->sum('chengben');
            $data_arr['goods_chengben'] = $chengben;
            $res = db('goods_spec_detail')->where('id',$post['id'])->update($data_arr);
            $res!==false?$this->success('保存成功',''):$this->error('保存失败，请稍后再试','');
        }else{
            $id = input('id');          //ys_goods_spec_detail  --- id
            $goods = db('goods_spec_detail')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->field('a.id,a.goods_id,b.name,a.title,a.peifang_ids')->where(['a.id'=>$id])->find();

            $goods['peifang_ids'] = explode(',',$goods['peifang_ids']);
            $peifang = db('goods_peifang')->where(['is_deleted'=>0,'store_id'=>session('user.store_id')])->select();

            $this->assign('peifang',$peifang);
            $this->assign('goods',$goods);
            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    发送审核申请
     * 2018-05-30
     */
    public function send_check(){
        $post = input('post.');
        $res = db('goods_spec_detail')->where('id',$post['id'])->update(['is_checked'=>1]);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }

    /**
     * 商品 -- 上架
     */
    public function on_sall()
    {
        $post = input('post.');
        $goods = db('store_goods_stock')->where('id',$post['id'])->field('id,goods_id')->find();
        db('store_goods_stock')->where('id',$post['id'])->update(['onsale'=>$post['value']]);
        $res = Db::name('goods')->where('id', $goods['goods_id'])->update(['status' => $post['value']]);

        $res !== false ? $this->success('上架成功', '') : $this->error('上架失败', '');
    }
    /**
     * 商品 -- 下架
     * @return [type] [description]
     */
    public function down_sall(){
        $post = input('post.');
        $goods = db('store_goods_stock')->where('id',$post['id'])->field('id,goods_id')->find();
        db('store_goods_stock')->where('id',$post['id'])->update(['onsale'=>$post['value']]);
        $res = Db::name('goods')->where('id', $goods['goods_id'])->update(['status' => $post['value']]);

        $res!==false?$this->success('下架成功',''):$this->error('下架失败，请稍后再试！','');
    }

    /**
     * @Author  lingyun
     * @Desc    设置安全库存
     * @return array|string
     */
    public function edit_warn_stock()
    {
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $res = db('store_goods_stock')->where('id',$post['id'])->update(['warn_stock'=>$post['warn_stock']]);
            $res!==false?$this->success('设置成功',''):$this->error('设置失败','');
        }else{
            $id = input('id');
            $vo = db('store_goods_stock')->where('id',$id)->find();
            $this->assign('vo',$vo);
            $this->assign('title','设置安全库存');
            $this->assign('id',$id);

            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    删除商品
     */
    public function del_goods(){
        $table = "Goods";
        if (DataService::update($table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    /**
     * @Author  lingyun
     * @Desc    店内商品库存明细
     * 2018-05-03
     */
    public function stock_log(){
        $id = input('id');          //商品id
        $goods = db('goods')->alias('a')->join('ys_goods_spec_detail b','a.id=b.goods_id','LEFT')->where('b.id',$id)->field('a.name,a.id,b.id as spec_id')->find();
        $store_id = session('user')['store_id'];

        $db = db('store_goods_log')->where(['goods_spec_id'=>$id,'store_id'=>$store_id])->order('id desc');

        $this->assign('title','店内商品 - '.$goods['name']);
        $this->assign('list',$goods);
        $this->assign('goods',$goods);
        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    预创建店内商品购货申请列表页面
     * 2018-05-03
     */
    public function application_goods(){
        $this->title = '待订货商品配方列表';
        $get = $this->request->get();

        $store_id = session('user')['store_id'];

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_category c', 'g.cat_id=c.id', 'LEFT'],
            ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
        ];

        $db = db('store_order_goods')->alias('a')->where('a.store_id', $store_id)->where('a.is_deleted', 0)->where('a.status', 0)->where('is_diannei',1)->field('g.name,c.title as cname,a.id,a.addtime,g.unit,a.num,s.title,a.signal_chengben,a.chengben')->join($join);
        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    创建店内购货申请商品信息
     */
    public function create_application_goods(){
        $store_id = session('user')['store_id'];
        if (request()->ispost()) {
            if (!input('goods_id'))
                $this->error('请选择一种商品');
            if (!input('goods_spec_id') && input('goods_id') && db('goods')->find(input('goods_id'))['is_spec'] == 1)
                $this->error('请选择一种属性');

            if (input('goods_spec_id')){
                $spec_id = input('goods_spec_id');
                $peifang_ids = db('goods_spec_detail')->where('id',$spec_id)->value('peifang_ids');
                if(!empty($peifang_ids)){
                    $sql = "select sum(chengben) as signal_chengben from ys_goods_peifang where id in (".$peifang_ids.")";
                    $signal_chengben = Db::query($sql)[0]['signal_chengben'];
                    $chengben = input('num')*$signal_chengben;
                }else{
                    $signal_chengben = 0;
                    $chengben = 0;
                }
            }else{
                $goods_spec_detail= db('goods_spec_detail')->where('goods_id',input('goods_id'))->where('specs',0)->field('id,peifang_ids')->find();
                $spec_id = $goods_spec_detail['id'];
                if(!empty($spec_id)){
                    $sql = "select sum(chengben) as signal_chengben from ys_goods_peifang where id in (".$goods_spec_detail['peifang_ids'].")";
                    $signal_chengben = Db::query($sql)[0]['signal_chengben'];
                    $chengben = input('num')*$signal_chengben;
                }else{
                    $signal_chengben = 0;
                    $chengben = 0;
                }
            }

            //订货配方
            $order_goods_id = db('store_order_goods')->insertGetId(['goods_id' => input('goods_id'), 'goods_spec_id' => $spec_id, 'num' => input('num'),'signal_chengben'=>$signal_chengben,'chengben'=>$chengben, 'store_id' => $store_id, 'addtime' => time(),'is_diannei'=>1]);

            if ($order_goods_id)
                $this->success('配方添加成功！', '');
        } else {
            $cat = db('goods_category')->where('is_exp',0)->select();
            $this->assign('cat', $cat);

            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    获取商品信息
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function goods()
    {
        $goods = db('goods')->where('cat_id', input('cat_id'))->where(['store_id'=>session('user')['store_id'],'is_deleted'=>0,'status'=>1])->select();
        return $goods;
    }

    /**
     * @Author  lingyun
     * @Desc    获取商品属性信息
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function spec()
    {
        $spec = db('goods_spec_detail')->where(['goods_id'=>input('goods_id'),'is_deleted'=>0])->select();
        return $spec;
    }

    /**
     * 编辑
     * @return array|string
     */
    public function edit()
    {
        if(request()->isPost()){
            $post =input('post.');
            $spec_id = db('store_order_goods')->where('id',$post['id'])->value('goods_spec_id');
            $peifang_ids = db('goods_spec_detail')->where('id',$spec_id)->value('peifang_ids');
            if(!empty($peifang_ids)){
                $sql = "select sum(chengben) as signal_chengben from ys_goods_peifang where id in (".$peifang_ids.")";
                $signal_chengben = Db::query($sql)[0]['signal_chengben'];
                $chengben = $post['num']*$signal_chengben;
            }else{
                $signal_chengben = 0;
                $chengben = 0;
            }

            $flag = db('store_order_goods')->where('id',$post['id'])->update(['num'=>$post['num'],'signal_chengben'=>$signal_chengben,'chengben'=>$chengben]);
            $flag!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }
        $table = "StoreOrderGoods";
        $cat = db('goods_category')->select();
        $this->assign('cat', $cat);

        return $this->_form($table, 'create_application_goods');
    }


    /**
     * 删除
     */
    public function del()
    {
        $id = input('id');
        $res = db('store_order_goods')->where('id',$id)->delete();
        $res>0?$this->success('删除成功',''):$this->error('删除成功','');
//        $table = "StoreOrderGoods";
//        if (DataService::update($table)) {
//            $this->success("配方删除成功！", '');
//        }
//        $this->error("配方删除失败，请稍候再试！");
    }

    /**
     * @Author  lingyun
     * @Desc    创建申请订单
     * 2018-05-03
     */
    public function create_order(){
        $table = "StoreOrderGoods";
        if (DataService::update($table)) {
            $sn = build_order_no();
            $store_id = session('user')['store_id'];
            $i = db('store_order')->insertGetId(['sn' => $sn, 'addtime' => time(), 'store_id' => $store_id,'is_diannei'=>1,'admin_id'=>session('user.id'),'deal_admin'=>session('user.id')]);


            $ids = input('id');
            $sql = "select sum(signal_chengben) as signal_chengben,sum(chengben) as chengben from ys_store_order_goods where id in (".$ids.")";
            $chengben_result = Db::query($sql);          //成本价
            db('store_order')->where('id',$i)->update(['chengben'=>$chengben_result[0]['chengben']]);

            $ids = explode(',', $ids);
            //遍历商品配方
            $status = 1;//循环报错为0
            foreach ($ids as $id) {
                $ret = db($table)->where('id', $id)->update(['order_id' => $i]);
                if ($ret === false)
                    $status = 0;
            }
            if ($status == 1)
                $this->success("订货单生成成功！", '');
        }
        $this->error("订货单生成失败，请稍候再试！");
    }


    /**
     * 店内商品订货申请订单
     * @return array
     * 2018-05-03
     */
    public function order()
    {
        $table = 'StoreOrder';
        $this->title = '订货单管理';
        $get = $this->request->get();

        $store_id = session('user')['store_id'];
        $is_jiameng = db('store')->where('id',$store_id)->value('is_jiameng');

        $db = Db::name($table)->order('id', 'desc')->where('store_id', $store_id)->where('is_diannei',1);
        foreach (['sn'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        $this->assign('is_jiameng',$is_jiameng);

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    购货订单详情
     * @return array|string
     */
    public function detail()
    {
        $join = [
            ['ys_goods m', 'a.goods_id=m.id', 'LEFT'],
            ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
        ];

        $order = db('store_order')->where('id',input('id'))->find();
        $db = db('StoreOrderGoods')->alias('a')->join($join)->where('order_id', input('id'))->field('a.*,m.*,s.*,m.good_number')->select();
        $store = db('store')->where('id',$order['store_id'])->find();

        $this->assign('list', $db);
        $this->assign('order', $order);
        $this->assign('store', $store);

        return $this->_form('store_material', 'detail');
    }

    /**
     * 确认收货
     * @return array|string
     * @throws \think\Exception
     */
    public function receive()
    {
        $store_id = session('user')['store_id'];

        if (request()->ispost()) {
            $post = input();

            $status = 1;//监控循环报错
            foreach ($post as $k => $v) {
                if (strrpos($k, 'num')) {
                    $id = explode('_', $k)[2];

                    $order_goods = db('store_order_goods')->where('id', $id)->find();
                    $i = db('store_order_goods')->update(['id' => $id, 'rec_num' => $v, 'dif_num' => $v - $order_goods['del_num'], 'rec_time' => time()]);
                    if ($i === false)
                        $status = 0;
                    //入库数大于0
                    if ($v > 0) {

                        $order_id = $post['order_id'];
                        $store_order = db('store_order')->where('id', $order_id)->find();
                        $sn = $store_order['sn'];

                        $store_goods_stock = db('store_goods_stock')->where('store_id', $store_id)->where('goods_id', $order_goods['goods_id'])->where('goods_spec_id' , $order_goods['goods_spec_id'])->find();
                        $title = $store_goods_stock['spec_title'];
                        if ($store_goods_stock) {
//                            $ii = db('store_goods_stock')->where('id', $store_goods_stock['id'])->setInc('stock', $v);        //2018-09-13

                            //2018-09-13    start
                            $goods_spec_detail = db('goods_spec_detail')->find($order_goods['goods_spec_id']);
                            $peifang = db('goods_peifang')->where('id','in',$goods_spec_detail['peifang_ids'])->field('sum(chengben) as chengben,sum(chengben_price) as chengben_price')->find();
                            $chengben = substr(sprintf("%.5f",($store_goods_stock['stock']*$store_goods_stock['chengben']+$v*$peifang['chengben'])/($store_goods_stock['stock']+$v)),0,-1);
                            $chengben_price = substr(sprintf("%.5f",($store_goods_stock['stock']*$store_goods_stock['chengben_price']+$v*$peifang['chengben_price'])/($store_goods_stock['stock']+$v)),0,-1);
                            $cur_stock = $store_goods_stock['stock']+$v;
                            $ii = db('store_goods_stock')->where('id', $store_goods_stock['id'])->update(['stock'=>$cur_stock,'chengben'=>$chengben,'chengben_price'=>$chengben_price]);
                            //2018-09-13    end
                            
                            $stock = $store_goods_stock['stock'] + $v;
                        } else {
                            //2018-09-13
//                            $goods_spec_detail = db('goods_spec_detail')->find($order_goods['goods_spec_id']);
//                            $title = $goods_spec_detail['title'];
//                            $ii = db('store_goods_stock')->insert([
//                                'store_id' => $order_goods['store_id'],
//                                'goods_id' => $order_goods['goods_id'],
//                                'goods_spec_id' => $order_goods['goods_spec_id'],
//                                'price'=>$goods_spec_detail['price'],
//                                'onsale' => 0,
//                                'stock' => $v,
//                                //追加
//                                'spec_title' => $goods_spec_detail['title'],
//                                'specs' => $goods_spec_detail['specs'],
//                                'addtime'=>time(),
//                                'is_diannei'=>$order_goods['is_diannei'],
//                                'is_deleted'=>0
//                            ]);

                            //2018-09-13    start
                            $goods_spec_detail = db('goods_spec_detail')->find($order_goods['goods_spec_id']);
                            $peifang = db('goods_peifang')->where('id','in',$goods_spec_detail['peifang_ids'])->field('sum(chengben) as chengben,sum(chengben_price) as chengben_price')->find();
                            $title = $goods_spec_detail['title'];
                            $ii = db('store_goods_stock')->insert([
                                'store_id' => $order_goods['store_id'],
                                'goods_id' => $order_goods['goods_id'],
                                'goods_spec_id' => $order_goods['goods_spec_id'],
                                'price'=>$goods_spec_detail['price'],
                                'onsale' => 0,
                                'stock' => $v,
                                //追加
                                'spec_title' => $goods_spec_detail['title'],
                                'specs' => $goods_spec_detail['specs'],
                                'addtime'=>time(),
                                'is_diannei'=>$order_goods['is_diannei'],
                                'is_deleted'=>0,
                                'chengben'=>$peifang['chengben'],
                                'chengben_price'=>$peifang['chengben_price']
                            ]);
                            //2018-09-13    end

                            $stock = $v;
                        }

                        if ($ii === false)
                            $status = 0;

                        $log = [
                            'store_id' => $order_goods['store_id'],
                            'goods_id' => $order_goods['goods_id'],
                            'goods_spec_id' => $order_goods['goods_spec_id'],
                            'title' => $title,
//                            'order_id' => $order_goods['order_id'],
                            'types' => 1,
                            'ruku_num' => $v,
//                            'remark' => $sn,
                            'remark' => '入库'.$v,
                            'addtime' => time(),
                            'cur_stock' => $stock,
                        ];
                        $iii = db('store_goods_log')->insert($log);
                        if ($iii === false)
                            $status = 0;
                    }
                }
            }

            if (db('store_order')->update(['id' => $post['order_id'],'deal_time'=>time(), 'status' => 3,'receive_time'=>time(),'receive_admin'=>session('user.id')])!==false && $status==1)
                $this->success('收货成功', '');

        } else {
            $join = [
                ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
                ['ys_goods_spec_detail s', 'a.goods_spec_id=s.id', 'LEFT'],
            ];
            $db = db('store_order_goods')->alias('a')->join($join)->where('a.order_id', input('id'))->field('a.id as oid,a.*,g.*,s.*')->select();

            $this->assign('list', $db);
            $this->assign('order_id', input('id'));

            return $this->_form('store_material_order', 'receive');
        }
    }


    /**
     * 调价
     * @return array|string
     */
    public function price()
    {
        $id = input('id');
        if (request()->ispost()) {
            $post = input('post.');

            $price = db('store_goods_stock')->alias('a')->join('goods_spec_detail b','a.goods_spec_id=b.id','LEFT')->where('a.id',$post['id'])->value('b.price');

            $trim_price = $post['trim_price']*$price/10;

            $stock = db('store_goods_stock')->where('id', $post['id'])->update(['trim_price' => 0,'discount'=>$post['trim_price']]);

            if ($stock !== false)
                $this->success('折扣设置成功！', '');
        } else {
            $store_goods = db('store_goods_stock')->where('id', $id)->find();

            $this->assign('store_goods', $store_goods);

            return $this->_form('store_goods_stock', 'price');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    订单对账
     * 2018-06-04
     */
    public function dz_chengben(){
        if(request()->isPost()){
            $post = input('post.');
            $dz_chengben = 0;
            foreach($post['id'] as $k => $v){
                $data[$k]['id'] = $v;
                $data[$k]['dz_signal_chengben'] = $post['dz_signal_chengben'][$k];
                $data[$k]['dz_chengben'] = $post['dz_chengben'][$k];
                $dz_chengben+=$post['dz_chengben'][$k];
            }
            $model = new StoreOrderGoods();
            $model->saveAll($data);         //更新对账成本
            $res = db('store_order')->where('id',$post['order_id'])->update(['dz_chengben'=>$dz_chengben,'dz_admin'=>session('user.id'),'dz_time'=>time()]);
            $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $order_id = input('id');
            $join = [
                ['ys_goods b','a.goods_id=b.id','LEFT'],
                ['ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT']
            ];

            $order = db('store_order')->where('id',$order_id)->field('id,sn,chengben')->find();
            $order_goods = db('store_order_goods')->alias('a')->join($join)->where('a.order_id',$order_id)->field('a.*,a.id as oid,b.name,c.title')->select();

//            $this->assign('title','对账'.$order['sn']);
            $this->assign('order_id',$order_id);
            $this->assign('list',$order_goods);
            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    商品报损
     * @return array|string
     */
    public function baosun()
    {
        $store_id = session('user')['store_id'];

        if (request()->ispost()) {
            $post = input('post.');
            $material_stock = db('store_goods_stock')->find($post['id']);
            $chengben = $material_stock['chegnben_price']*$post['loss'];

            $stock = db('store_goods_stock')->where('id', $post['id'])->setDec('stock', $post['loss']);
            $log = db('store_goods_log')->insert(['store_id' => $store_id, 'goods_id' => $material_stock['goods_id'],'types'=>0, 'sunhao_num' => $post['loss'], 'cur_stock' => $material_stock['stock'] - $post['loss'], 'addtime' => time(), 'remark' => $post['reason'], 'goods_spec_id' => $material_stock['goods_spec_id'], 'title' => $material_stock['spec_title'],'chengben'=>$chengben]);

            if ($stock !== false && $log !== false)
                $this->success('商品报损成功！', '');
        } else {
            return $this->_form('store_goods_stock', 'baosun');
        }
    }

}